<script lang="ts" setup>
import { COUNTRIES_LIST } from '@/constants/countries';
import { useRouter } from '@/router';
import { useAuthStore } from '@/store/auth';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { useLocale } from '@/locale/locale';
import { isWechat } from '@/utils/platform';

const { t } = useLocale();
const router = useRouter();
const authStore = useAuthStore();
const type = ref('');
const code = ref('');

function handleCountryChoose(country: any) {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 2];
  if (type.value == 'carBooker') {
    currentPage.$vm.changeBookerPhoneArea(country.code);
    uni.navigateBack();
  } else if (type.value == 'carEmergency') {
    currentPage.$vm.changeEmergencyPhoneArea(country.code);
    uni.navigateBack();
  } else if (type.value == 'intentionCountry') {
    currentPage.$vm.changeCountry(country.name, country.code);
    uni.navigateBack();
  } else if (type.value == 'intentionPhoneArea') {
    currentPage.$vm.changePhoneArea(country.code);
    uni.navigateBack();
  } else {
    authStore.setCountryPrefix(country.code, country.name);
  }
}

onLoad(async (options) => {
  type.value = options!.type;
  if (options!.type) {
    if (options!.type == 'intentionCountry') {
      code.value = options!.code ? options!.code : '';
    } else {
      code.value = options!.code ? options!.code : authStore.loginForm.countryPrefix;
    }
  } else {
    code.value = authStore.loginForm.countryPrefix;
  }
});
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :border="false"
    :title="t('LLKey_selectCountry')"
    fixed
    left-icon="back"
    shadow
    status-bar
    @click-left="router.back"
  />

  <view class="py-2 bg-white">
    <view
      v-for="country in COUNTRIES_LIST"
      :key="country.countryCode"
      class="country-list-item"
      @click.stop="() => handleCountryChoose(country)"
    >
      <view :class="code === country.code ? 'active' : ''">
        {{ country.name }}
      </view>
      <view :class="code === country.code ? 'active' : ''">
        {{ country.code }}
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.country-list-item {
  align-items: center;
  display: flex;
  justify-content: space-between;
  padding: 0 32rpx;

  view {
    color: #3d3d3d;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 100rpx;

    &.active {
      color: #269c74;
      font-weight: 500;
    }
  }
}
</style>
